﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NhanAi.Entity;
using NhanAi.DAO;
using Home.Utils;
using NhanAi.App_Code;
namespace NhanAi.Admin
{
    public partial class EditTaxonomy : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Authenticate();
            TaxonomyDao dao = new TaxonomyDao();
            int id = Request["id"] == null ? 0 : int.Parse(Request["id"]);
            Taxonomy t = dao.Read(id, NAConstants.ALL_LANGUAGE);
            hdnId.Value = id.ToString();
            if (!IsPostBack)
            {
                txtDescription.Text = t.Description;                
                txtTermName.Text = t.TermName;
                txtTermNameEn.Text = t.TermNameEn;
                List<Taxonomy> list = dao.ReadAll();
                Taxonomy empty = new Taxonomy();
                empty.TermName = "[Trống]";
                list.Insert(0, empty);
                cmbParent.DataSource = list;
                cmbParent.DataValueField = "Id";
                cmbParent.DataTextField = "TermName";
                cmbParent.DataBind();
                int i = 0;
                foreach (Taxonomy tax in list)
                {
                    if (t.ParentId == tax.Id) { cmbParent.SelectedIndex = i; }
                    i++;
                }
            }
            SetCurrentPage("Taxonomy");
        }

       
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            TaxonomyDao dao = new TaxonomyDao();
            Taxonomy t;
            try
            {
                int id = int.Parse(hdnId.Value);

                t = dao.Read(id, NAConstants.LANGUAGE_VI);
                t.ParentId = cmbParent.SelectedItem != null ? Int32.Parse(cmbParent.SelectedItem.Value) : 0;
                t.TermName = txtTermName.Text;
                t.TermNameEn = txtTermNameEn.Text;
                t.Description = txtDescription.Text;              
                t.Count = 0;
                t.TaxonomyType = "taxonomy";
                dao.Update(t);
            }
            catch (Exception ex)
            {
                Session["message"] = "Đã xảy ra lỗi";
            }
            Session["message"] = "Thêm mới thành công";
        }
    }
}